package com.exp.bookhouse.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;
/**
 * @Auther L_geng
 * @Date 2020/12/26
 */

/**
 * 七牛云图片操作工具类, 写在服务端
 */
public class QiniuUtil {

    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "0TvZI5i3eS4r5lfhWVjD4ERNzrCwRvaGah86in3c";
    private static final String SECRET_KEY = "McZWzRU260lJZlF8AyCdFnMmQPrhcl3zOIhZ-hn4";

    // 要上传的空间名称
    private static final String BUCKETNAME = "bbfeng";

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 外链默认域名
    private static final String DOMAIN = "http://qlwdwvwug.hn-bkt.clouddn.com";

    //组名
    private static String group = "bookstore";

    /**
     * 将图片上传到七牛云
     */
    public static String uploadQNImg(InputStream file, String key) {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
//        Configuration cfg = new Configuration(Zone.zone0());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(new Configuration());
        // 生成上传凭证，然后准备上传

        try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(BUCKETNAME);
            try {
                Response response = uploadManager.put(file, key, upToken, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                String returnPath = DOMAIN +"/"+ putRet.key;
                // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 通过key删除七牛云上的图片
     */
    public void delete(String key) throws QiniuException {

//        Configuration cfg = new Configuration(Region.region0());
        //创建凭证
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        try {
            bucketManager.delete(BUCKETNAME, key);//尝试删除图片
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}